<?php
session_start();
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header('Location: index.php');
    exit;
}

require_once __DIR__ . '/../core/config.php';
try {
    $db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET, DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    // 统计数据
    $stats = [];
    $stmt = $db->query("SELECT COUNT(*) as total FROM plugins");
    $stats['total_plugins'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    $stmt = $db->query("SELECT COUNT(*) as active FROM plugins WHERE status = 'active'");
    $stats['active_plugins'] = $stmt->fetch(PDO::FETCH_ASSOC)['active'];
    $stmt = $db->query("SELECT SUM(views) as total_views FROM plugins");
    $stats['total_views'] = $stmt->fetch(PDO::FETCH_ASSOC)['total_views'] ?: 0;
    $stmt = $db->query("SELECT SUM(likes) as total_likes FROM plugins");
    $stats['total_likes'] = $stmt->fetch(PDO::FETCH_ASSOC)['total_likes'] ?: 0;
    $stmt = $db->query("SELECT COUNT(*) as total FROM categories");
    $stats['total_categories'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
    $stmt = $db->query("SELECT name, views, likes FROM plugins WHERE status = 'active' ORDER BY views DESC LIMIT 10");
    $stats['popular_plugins'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt = $db->query("SELECT c.name, COUNT(pc.plugin_id) as plugin_count FROM categories c LEFT JOIN plugin_categories pc ON c.id = pc.category_id GROUP BY c.id ORDER BY plugin_count DESC");
    $stats['category_stats'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $stmt = $db->query("SELECT DATE(created_at) as date, COUNT(*) as count FROM access_logs WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) GROUP BY DATE(created_at) ORDER BY date");
    $stats['daily_visits'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo '<div class="bg-red-100 text-red-700 p-4 rounded mb-4">SQL错误：' . htmlspecialchars($e->getMessage()) . '</div>';
    exit;
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据统计 - 幻影工具网</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body class="bg-gray-50 min-h-screen">
    <!-- 顶部导航 -->
    <nav class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-10">
        <div class="max-w-7xl mx-auto px-4 flex justify-between items-center h-16">
            <h1 class="text-xl font-bold text-blue-700">幻影工具网后台</h1>
            <div class="flex items-center space-x-4">
                <a href="/" class="text-gray-600 hover:text-blue-700">返回前台</a>
                <a href="logout.php" class="text-red-600 hover:text-red-800">退出登录</a>
            </div>
        </div>
    </nav>
    <div class="flex min-h-screen">
        <!-- 侧边栏 -->
        <aside class="w-64 bg-white shadow-md hidden md:block">
            <nav class="mt-8 space-y-2 px-4">
                <a href="index.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">仪表盘</a>
                <a href="plugins.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">插件管理</a>
                <a href="categories.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">分类管理</a>
                <a href="stats.php" class="block px-4 py-2 rounded-lg bg-blue-50 text-blue-700 font-bold">数据统计</a>
                <a href="logs.php" class="block px-4 py-2 rounded-lg text-gray-600 hover:bg-blue-50 hover:text-blue-700">操作日志</a>
            </nav>
        </aside>
        <!-- 主内容区 -->
        <main class="flex-1 p-6">
            <div class="mb-8">
                <h2 class="text-2xl font-bold text-gray-900 mb-2">数据统计</h2>
                <p class="text-gray-500">查看网站各项数据统计和分析</p>
            </div>
            <!-- 统计卡片 -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <div class="bg-white rounded-xl shadow p-6 flex items-center">
                    <div class="p-3 rounded-full bg-blue-100 text-blue-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">总插件数</p>
                        <p class="text-2xl font-semibold text-gray-900"><?php echo number_format($stats['total_plugins']); ?></p>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow p-6 flex items-center">
                    <div class="p-3 rounded-full bg-green-100 text-green-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">启用插件</p>
                        <p class="text-2xl font-semibold text-gray-900"><?php echo number_format($stats['active_plugins']); ?></p>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow p-6 flex items-center">
                    <div class="p-3 rounded-full bg-purple-100 text-purple-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">总浏览量</p>
                        <p class="text-2xl font-semibold text-gray-900"><?php echo number_format($stats['total_views']); ?></p>
                    </div>
                </div>
                <div class="bg-white rounded-xl shadow p-6 flex items-center">
                    <div class="p-3 rounded-full bg-yellow-100 text-yellow-600">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"></path>
                        </svg>
                    </div>
                    <div class="ml-4">
                        <p class="text-sm font-medium text-gray-600">总点赞数</p>
                        <p class="text-2xl font-semibold text-gray-900"><?php echo number_format($stats['total_likes']); ?></p>
                    </div>
                </div>
            </div>
            <!-- 图表区域 -->
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
                <!-- 访问趋势图 -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">最近7天访问趋势</h3>
                    <canvas id="visitChart" width="400" height="200"></canvas>
                </div>
                <!-- 分类统计图 -->
                <div class="bg-white rounded-xl shadow p-6">
                    <h3 class="text-lg font-semibold text-gray-900 mb-4">分类插件分布</h3>
                    <canvas id="categoryChart" width="400" height="200"></canvas>
                </div>
            </div>
            <!-- 热门插件 -->
            <div class="bg-white rounded-xl shadow p-6">
                <h3 class="text-lg font-semibold text-gray-900 mb-4">热门插件排行</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">排名</th>
                                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">插件名称</th>
                                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">浏览量</th>
                                <th class="px-6 py-3 text-left text-xs font-bold text-gray-500 uppercase">点赞数</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-100">
                            <?php foreach ($stats['popular_plugins'] as $index => $plugin): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center justify-center w-8 h-8 rounded-full <?php echo $index < 3 ? 'bg-yellow-100 text-yellow-800' : 'bg-gray-100 text-gray-800'; ?> text-sm font-medium"><?php echo $index + 1; ?></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-bold text-gray-900"><?php echo htmlspecialchars($plugin['name']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo number_format($plugin['views']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500"><?php echo number_format($plugin['likes']); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <script>
                // 访问趋势图
                const visitCtx = document.getElementById('visitChart').getContext('2d');
                const visitChart = new Chart(visitCtx, {
                    type: 'line',
                    data: {
                        labels: <?php echo json_encode(array_column($stats['daily_visits'], 'date')); ?>,
                        datasets: [{
                            label: '访问量',
                            data: <?php echo json_encode(array_column($stats['daily_visits'], 'count')); ?>,
                            borderColor: 'rgb(59, 130, 246)',
                            backgroundColor: 'rgba(59, 130, 246, 0.1)',
                            tension: 0.1
                        }]
                    },
                    options: {
                        responsive: true,
                        scales: { y: { beginAtZero: true } }
                    }
                });
                // 分类统计图
                const categoryCtx = document.getElementById('categoryChart').getContext('2d');
                const categoryChart = new Chart(categoryCtx, {
                    type: 'doughnut',
                    data: {
                        labels: <?php echo json_encode(array_column($stats['category_stats'], 'name')); ?>,
                        datasets: [{
                            data: <?php echo json_encode(array_column($stats['category_stats'], 'plugin_count')); ?>,
                            backgroundColor: [
                                '#3B82F6','#10B981','#F59E0B','#EF4444','#8B5CF6','#06B6D4','#84CC16','#F97316'
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { position: 'bottom' } }
                    }
                });
            </script>
        </main>
    </div>
</body>
</html> 